package com.ssy.lingxi.message.websocket.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import lombok.extern.slf4j.Slf4j;

/**
 * json工具类
 * @author yzc
 * @version 2.0.0
 * @date 2021/3/26
 */
@Slf4j
public class JsonUtil {

    private static final ObjectMapper mapper = new ObjectMapper();

    public static String toJsonStr(Object object) {
        try {
            return mapper.writeValueAsString(object);

        } catch (JsonProcessingException e) {
            log.error("序列化json异常", e);
            throw new BusinessException(ResponseCode.BUSINESS_ERROR);
        }
    }

    public static <T> T toBean(String jsonStr, Class<T> clazz) {
        try {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return mapper.readValue(jsonStr, clazz);
        } catch (JsonProcessingException e) {
            log.error("解析json异常", e);
            throw new BusinessException(ResponseCode.BUSINESS_ERROR);
        }
    }
}
